package cn.yunhe.service;

import cn.yunhe.dao.ProductCategoryDao;
import cn.yunhe.entity.Page;
import cn.yunhe.entity.ProductCategory;
import cn.yunhe.util.PageUtil;
import cn.yunhe.util.SqlSessionFactoryUtil;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class ProductCategoryService {

    private SqlSession session = null;
    private ProductCategoryDao pcd = null;

    private void init(){
        session = SqlSessionFactoryUtil.getSession();
        pcd = session.getMapper(ProductCategoryDao.class);
    }

    private void destroy(){
        session.close();
    }

    public List<ProductCategory> getParents(){
        init();
        List<ProductCategory>list = pcd.getParents();
        destroy();
        return list;
    }

    public List<ProductCategory> getCategoryByPid(int pid){
        init();
        List<ProductCategory>list = pcd.getCategoryByPid(pid);
        destroy();
        return list;
    }

    public boolean addCategory(ProductCategory pc){
        init();
        boolean b = pcd.addCategory(pc);
        session.commit();
        destroy();
        return b;
    }

    public int getEpcid(String epcname){
        init();
        int epcid = pcd.getEpcid(epcname);
        destroy();
        return epcid;
    }

    public boolean modifyEpcpartentid(int epcid){
        init();
        boolean b = pcd.modifyEpcpartentid(epcid);
        session.commit();
        destroy();
        return b;
    }

    public List<ProductCategory> getAllCategory(){
        init();
        List<ProductCategory>list = pcd.getAllCategory();
        destroy();
        return list;
    }

    public ProductCategory getCategoryById(int epcid){
        init();
        ProductCategory pc = pcd.getCategoryById(epcid);
        destroy();
        return pc;
    }

    public  boolean modifyCategory(ProductCategory pc){
        init();
        boolean b = pcd.modifyCategory(pc);
        session.commit();
        destroy();
        return b;
    }

    public int getParentId(int epcid){
        init();
        int eid = pcd.getParentId(epcid);
        destroy();
        return eid;
    }

    public boolean deleteCategory(int epcid){
        init();
        boolean b = pcd.deleteCategory(epcid);
        session.commit();
        destroy();
        return b;
    }

    public List<ProductCategory> getCategoryByPage(int pageIndex){
        init();
        Page page = new Page();
        page.setPageStart(PageUtil.PAGE_SIZE*(pageIndex-1));
        page.setPageSize(PageUtil.PAGE_SIZE);
        List<ProductCategory>list = pcd.getCategoryByPage(page);
        destroy();
        return list;
    }

    public int getCategoryCount(){
        init();
        int count = pcd.getCategoryCount();
        destroy();
        return count;
    }
}
